/*
 * AppPrefs.java
 *
 * Created on July 17, 2006, 10:41 AM
 */

package org.vcboard.view;

import java.awt.event.KeyEvent;
import java.io.FileOutputStream;
import java.sql.Connection;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import org.apache.log4j.*;
import org.vcboard.*;
import org.vcboard.database.*;
import org.vcboard.model.*;

/**
 *
 * @author  Josh
 */
public class AppPrefs extends javax.swing.JFrame
{
   
   private static Logger log = Logger.getLogger(AppPrefs.class);
   
   /**
    * Creates new form AppPrefs
    */
   public AppPrefs()
   {
      initComponents();
      
      WorkTimer.centerForm(this);
      updatePrefs();
   }
   
   private void updatePrefs()
   {
      dbHostTextField.setText(WorkTimer.getProperties().getProperty("DB_HOST", "localhost"));
      dbUserTextField.setText(WorkTimer.getProperties().getProperty("DB_USER", "root"));
      dbPassTextField.setText(WorkTimer.getProperties().getProperty("DB_PASS", "password"));
      dbNameTextField.setText(WorkTimer.getProperties().getProperty("DB_NAME", "work_timer"));
   }
   
   private boolean checkDBPrefsChanged()
   {
      boolean retVal = false;
      
      // Check to see if any of the existing preferences are different from the 
      //  values in the text fields
      if (!WorkTimer.getProperties().getProperty("DB_HOST").equals(dbHostTextField.getText()))
      {
         retVal = true;
      }
      
      if (!WorkTimer.getProperties().getProperty("DB_USER").equals(dbUserTextField.getText()))
      {
         retVal = true;
      }
      
      char[] dbPassC = dbPassTextField.getPassword();
      String dbPass = new String(dbPassC);
      
      if (!WorkTimer.getProperties().getProperty("DB_PASS").equals(dbPass))
      {
         retVal = true;
      }
      
      if (!WorkTimer.getProperties().getProperty("DB_NAME").equals(dbNameTextField.getText()))
      {
         retVal = true;
      }
      
      return retVal;
   }
   
   private void savePrefs()
   {
      if (!dbHostTextField.getText().equals(""))
      {
         log.info("Saving preferences");
         
         if (WorkTimer.getUser().getUserId() != -1)
         {
            WorkTimer.resetTimeout();
            
            // Save timeout info
            WorkTimer.getUser().setTimeoutEnabled(timedLogOutCheckBox.isSelected());
            WorkTimer.getUser().setTimeout(Long.parseLong(loginTimeoutTextField.getText()) * 60);
            WorkTimer.getUser().setOffset(Integer.parseInt(timeOffsetTextField.getText()));
         
            // Persist
            MySQLDbIf.getInstance().updateTimeout(timedLogOutCheckBox.isSelected(), 
                  loginTimeoutTextField.getText());
            MySQLDbIf.getInstance().updateOffset(timeOffsetTextField.getText());
         }
         
         // Check to see if database preferences have changed
         if (checkDBPrefsChanged())
         {
            char[] dbPassC = dbPassTextField.getPassword();
            String dbPass = new String(dbPassC);
            WorkTimer.getProperties().setProperty("DB_HOST", dbHostTextField.getText());
            WorkTimer.getProperties().setProperty("DB_USER", dbUserTextField.getText());
            WorkTimer.getProperties().setProperty("DB_PASS", dbPass);
            WorkTimer.getProperties().setProperty("DB_NAME", dbNameTextField.getText());
         
            try
            {
               FileOutputStream out = new FileOutputStream("settings.ini");
               WorkTimer.getProperties().store(out, "--- WorkTimer Properties ---");
               out.close();
            }
            catch (Exception e)
            {
               log.error("Failed to save settings to file");
               JOptionPane.showMessageDialog(null,
                     "Failed to save settings to file.  You will have to try again.",
                     "Error",
                     JOptionPane.ERROR_MESSAGE);
            }
         
            MySQLDbIf.getInstance().regetMySQLConn();
            
            if (!MySQLDbIf.getInstance().tablesExist())
            {
               String[] options = {"Yes", "No"};
      
               int response = JOptionPane.showOptionDialog(null,
                     "The specified database does not contain the required " +
                     "tables to operate with this application.\n\n" +
                     "Would you like me to attempt to install them for you?",
                     "Notice",
                     JOptionPane.YES_NO_OPTION,
                     JOptionPane.QUESTION_MESSAGE,
                     null,
                     options,
                     options[0]);

               if (response == JOptionPane.YES_OPTION)
               {
                  log.info("Attempting to install tables...");
                  MySQLDbIf.getInstance().installTables();
               }
            }

            if (WorkTimer.getUser().getUserId() != -1)
            {
               // Notify logged in user that they need to relogin
               JOptionPane.showMessageDialog(null,
                     "You must login again to apply the changes.",
                     "Notice",
                     JOptionPane.INFORMATION_MESSAGE);
               WorkTimer.setUser(new User());
            }
         }
         
         setVisible(false);
      }
      else
      {
         JOptionPane.showMessageDialog(null,
               "Please enter the hostname of the database server!",
               "Save Preferences Error",
               JOptionPane.ERROR_MESSAGE);
      }
   }
   
   /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    */
   // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
   private void initComponents()
   {
      saveButton = new javax.swing.JButton();
      cancelButton = new javax.swing.JButton();
      preferencesTabPane = new javax.swing.JTabbedPane();
      generalTabPanel = new javax.swing.JPanel();
      timedLogOutCheckBox = new javax.swing.JCheckBox();
      loginTimeoutTextField = new javax.swing.JTextField();
      loginTimeoutLabel = new javax.swing.JLabel();
      jLabel6 = new javax.swing.JLabel();
      timeOffsetTextField = new javax.swing.JTextField();
      jLabel7 = new javax.swing.JLabel();
      databaseTabPanel = new javax.swing.JPanel();
      dbNameTextField = new javax.swing.JTextField();
      jLabel1 = new javax.swing.JLabel();
      jLabel5 = new javax.swing.JLabel();
      jLabel2 = new javax.swing.JLabel();
      jLabel3 = new javax.swing.JLabel();
      jLabel4 = new javax.swing.JLabel();
      dbHostTextField = new javax.swing.JTextField();
      dbUserTextField = new javax.swing.JTextField();
      dbPassTextField = new javax.swing.JPasswordField();
      testButton = new javax.swing.JButton();

      setTitle("Connection Properties");
      setResizable(false);
      saveButton.setText("Save");
      saveButton.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            saveButtonActionPerformed(evt);
         }
      });

      cancelButton.setText("Cancel");
      cancelButton.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            cancelButtonActionPerformed(evt);
         }
      });

      timedLogOutCheckBox.setText("Automatically logout of the program if I do nothing for");
      timedLogOutCheckBox.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
      timedLogOutCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));

      loginTimeoutLabel.setText("minutes");

      jLabel6.setText("Time offset from server:");

      jLabel7.setText("hours");

      org.jdesktop.layout.GroupLayout generalTabPanelLayout = new org.jdesktop.layout.GroupLayout(generalTabPanel);
      generalTabPanel.setLayout(generalTabPanelLayout);
      generalTabPanelLayout.setHorizontalGroup(
         generalTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(generalTabPanelLayout.createSequentialGroup()
            .addContainerGap()
            .add(generalTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
               .add(timedLogOutCheckBox)
               .add(generalTabPanelLayout.createSequentialGroup()
                  .add(17, 17, 17)
                  .add(generalTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                     .add(jLabel6)
                     .add(generalTabPanelLayout.createSequentialGroup()
                        .add(loginTimeoutTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 35, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(loginTimeoutLabel))
                     .add(generalTabPanelLayout.createSequentialGroup()
                        .add(timeOffsetTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 35, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabel7)))))
            .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      );
      generalTabPanelLayout.setVerticalGroup(
         generalTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(generalTabPanelLayout.createSequentialGroup()
            .addContainerGap()
            .add(timedLogOutCheckBox)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(generalTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(loginTimeoutTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(loginTimeoutLabel))
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(jLabel6)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(generalTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(timeOffsetTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(jLabel7))
            .addContainerGap(76, Short.MAX_VALUE))
      );
      preferencesTabPane.addTab("General", generalTabPanel);

      dbNameTextField.addFocusListener(new java.awt.event.FocusAdapter()
      {
         public void focusGained(java.awt.event.FocusEvent evt)
         {
            highlightText(evt);
         }
      });
      dbNameTextField.addKeyListener(new java.awt.event.KeyAdapter()
      {
         public void keyReleased(java.awt.event.KeyEvent evt)
         {
            handleEnter(evt);
         }
      });

      jLabel1.setText("Please enter the connection values for your database:");

      jLabel5.setText("Database Name:");

      jLabel2.setText("Database Host:");

      jLabel3.setText("Username:");

      jLabel4.setText("Password:");

      dbHostTextField.addFocusListener(new java.awt.event.FocusAdapter()
      {
         public void focusGained(java.awt.event.FocusEvent evt)
         {
            highlightText(evt);
         }
      });
      dbHostTextField.addKeyListener(new java.awt.event.KeyAdapter()
      {
         public void keyReleased(java.awt.event.KeyEvent evt)
         {
            handleEnter(evt);
         }
      });

      dbUserTextField.addFocusListener(new java.awt.event.FocusAdapter()
      {
         public void focusGained(java.awt.event.FocusEvent evt)
         {
            highlightText(evt);
         }
      });
      dbUserTextField.addKeyListener(new java.awt.event.KeyAdapter()
      {
         public void keyReleased(java.awt.event.KeyEvent evt)
         {
            handleEnter(evt);
         }
      });

      dbPassTextField.setFont(new java.awt.Font("Tahoma", 0, 11));
      dbPassTextField.addFocusListener(new java.awt.event.FocusAdapter()
      {
         public void focusGained(java.awt.event.FocusEvent evt)
         {
            highlightText(evt);
         }
      });

      testButton.setText("Test");
      testButton.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            testButtonActionPerformed(evt);
         }
      });

      org.jdesktop.layout.GroupLayout databaseTabPanelLayout = new org.jdesktop.layout.GroupLayout(databaseTabPanel);
      databaseTabPanel.setLayout(databaseTabPanelLayout);
      databaseTabPanelLayout.setHorizontalGroup(
         databaseTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(databaseTabPanelLayout.createSequentialGroup()
            .addContainerGap()
            .add(databaseTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
               .add(jLabel1)
               .add(databaseTabPanelLayout.createSequentialGroup()
                  .add(databaseTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                     .add(jLabel4)
                     .add(jLabel2)
                     .add(jLabel3)
                     .add(jLabel5))
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                  .add(databaseTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                     .add(databaseTabPanelLayout.createSequentialGroup()
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(dbHostTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE))
                     .add(dbUserTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)
                     .add(dbNameTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)
                     .add(dbPassTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)))
               .add(org.jdesktop.layout.GroupLayout.TRAILING, testButton))
            .addContainerGap())
      );
      databaseTabPanelLayout.setVerticalGroup(
         databaseTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(databaseTabPanelLayout.createSequentialGroup()
            .addContainerGap()
            .add(jLabel1)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(databaseTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(jLabel2)
               .add(dbHostTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(databaseTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(jLabel3)
               .add(dbUserTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(databaseTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(jLabel4)
               .add(dbPassTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(databaseTabPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(dbNameTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(jLabel5))
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(testButton)
            .addContainerGap(16, Short.MAX_VALUE))
      );
      preferencesTabPane.addTab("Database Properties", databaseTabPanel);

      org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
         layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
            .addContainerGap()
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
               .add(org.jdesktop.layout.GroupLayout.LEADING, preferencesTabPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE)
               .add(layout.createSequentialGroup()
                  .add(saveButton)
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                  .add(cancelButton)))
            .addContainerGap())
      );
      layout.setVerticalGroup(
         layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(layout.createSequentialGroup()
            .addContainerGap()
            .add(preferencesTabPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 199, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(saveButton)
               .add(cancelButton))
            .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      );
      pack();
   }// </editor-fold>//GEN-END:initComponents

   private void handleEnter(java.awt.event.KeyEvent evt)//GEN-FIRST:event_handleEnter
   {//GEN-HEADEREND:event_handleEnter
      if (evt.getKeyCode() == KeyEvent.VK_ENTER)
      {
         savePrefs();
      }
   }//GEN-LAST:event_handleEnter

   private void highlightText(java.awt.event.FocusEvent evt)//GEN-FIRST:event_highlightText
   {//GEN-HEADEREND:event_highlightText
      ((JTextField) evt.getSource()).setSelectionStart(0);
   }//GEN-LAST:event_highlightText

   private void testButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_testButtonActionPerformed
   {//GEN-HEADEREND:event_testButtonActionPerformed
      testConnection();
   }//GEN-LAST:event_testButtonActionPerformed

   private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cancelButtonActionPerformed
   {//GEN-HEADEREND:event_cancelButtonActionPerformed
      setVisible(false);
   }//GEN-LAST:event_cancelButtonActionPerformed

   private void saveButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_saveButtonActionPerformed
   {//GEN-HEADEREND:event_saveButtonActionPerformed
      savePrefs();
   }//GEN-LAST:event_saveButtonActionPerformed
   
   /**
    * @param args the command line arguments
    */
   public static void main(String args[])
   {
      java.awt.EventQueue.invokeLater(new Runnable()
      {
         public void run()
         {
            new AppPrefs().setVisible(true);
         }
      });
   }
   
   private boolean testConnection()
   {
      boolean retVal = false;
      char[] dbPassC = dbPassTextField.getPassword();
      String dbPass = new String(dbPassC);
      
      Connection test = MySQLDbIf.getInstance().testMySQLConn(
            dbHostTextField.getText(),
            dbUserTextField.getText(),
            dbPass,
            dbNameTextField.getText());
      
      if (test != null)
      {
         JOptionPane.showMessageDialog(null,
               "Connection successful!",
               "Success",
               JOptionPane.INFORMATION_MESSAGE);
      }
      else
      {
         JOptionPane.showMessageDialog(null,
               "Connection failed!",
               "Error",
               JOptionPane.ERROR_MESSAGE);
      }
      
      return retVal;
   }

   public void setVisible(boolean b)
   {
      super.setVisible(b);
      WorkTimer.resetTimeout();
      
      if (WorkTimer.getUser().getUserId() != -1)
      {
         preferencesTabPane.add("General", generalTabPanel);
         preferencesTabPane.setSelectedComponent(generalTabPanel);
         timeOffsetTextField.setText(String.valueOf(WorkTimer.getUser().getOffset()));
         timedLogOutCheckBox.setSelected(WorkTimer.getUser().isTimeoutEnabled());
         loginTimeoutTextField.setText(String.valueOf(WorkTimer.getUser().getTimeout() / 60));
      }
      else
      {
         preferencesTabPane.removeAll();
         preferencesTabPane.add("Database Settings", databaseTabPanel);
      }
   }
   
   // Variables declaration - do not modify//GEN-BEGIN:variables
   private javax.swing.JButton cancelButton;
   private javax.swing.JPanel databaseTabPanel;
   private javax.swing.JTextField dbHostTextField;
   private javax.swing.JTextField dbNameTextField;
   private javax.swing.JPasswordField dbPassTextField;
   private javax.swing.JTextField dbUserTextField;
   private javax.swing.JPanel generalTabPanel;
   private javax.swing.JLabel jLabel1;
   private javax.swing.JLabel jLabel2;
   private javax.swing.JLabel jLabel3;
   private javax.swing.JLabel jLabel4;
   private javax.swing.JLabel jLabel5;
   private javax.swing.JLabel jLabel6;
   private javax.swing.JLabel jLabel7;
   private javax.swing.JLabel loginTimeoutLabel;
   private javax.swing.JTextField loginTimeoutTextField;
   private javax.swing.JTabbedPane preferencesTabPane;
   private javax.swing.JButton saveButton;
   private javax.swing.JButton testButton;
   private javax.swing.JTextField timeOffsetTextField;
   private javax.swing.JCheckBox timedLogOutCheckBox;
   // End of variables declaration//GEN-END:variables
   
}
